#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QLocale>
#include <QTranslator>
#include <QQmlContext>
#include <QThreadPool>
#include "NodeController/NodeControllerTask.h"
#include "DataManager/DataManager.h"
// #include "NodeController/NodeControllerManager.h"
// #include "PTZCamera/PTZCameraTask.h"
// #include "Database/DatabaseTask.h"
// #include "Encoding/EncodingTask.h"

int main(int argc, char *argv[])
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
    QGuiApplication app(argc, argv);

    // 注册 QAbstractSocket::SocketError 类型 -- 处理tcp连接错误情况
    qRegisterMetaType<QAbstractSocket::SocketError>("QAbstractSocket::SocketError");

    // 初始化翻译器
    QTranslator translator;
    const QStringList uiLanguages = QLocale::system().uiLanguages();
    for (const QString &locale : uiLanguages) {
        const QString baseName = "MultiPerceptionServer_" + QLocale(locale).name();
        if (translator.load(":/i18n/" + baseName)) {
            app.installTranslator(&translator);
            break;
        }
    }

    // 初始化线程池
    QThreadPool* threadPool = QThreadPool::globalInstance();
    threadPool->setMaxThreadCount(100);  // 设置最大线程数

    // 创建 DataManager 对象
    DataManager dataManager;

    // 模拟连接到多个远程节点控制器
    QString host = "192.168.1.91";  // 示例 IP 地址
    int port = 12345;                 // 示例端口
    for (int i = 0; i < 20; ++i)
    {
        NodeControllerTask* nodeTask = new NodeControllerTask(i, host, port);
        QObject::connect(nodeTask, &NodeControllerTask::dataReady, &dataManager, &DataManager::processData, Qt::QueuedConnection);
        // TODO
        // QObject::connect(nodeTask, &NodeControllerTask::dataReady, [threadPool](const QMap<int, QString>& data) {
        //     // 当所有节点数据准备好时，提交数据库和编码任务
        //     DatabaseTask* dbTask = new DatabaseTask(data);
        //     threadPool->start(dbTask);

        //     EncodingTask* encodingTask = new EncodingTask(data);
        //     threadPool->start(encodingTask);
        // });
        threadPool->start(nodeTask);
    }

    // TODO
    // // 模拟云台摄像机控制任务
    // QTimer::singleShot(5000, [threadPool]() {
    //     PTZCameraTask* ptzTask = new PTZCameraTask("MOVE_UP");
    //     threadPool->start(ptzTask);
    // });

    QQmlApplicationEngine engine;
    // // 获取 QML 上下文并设置上下文属性 -- 作用于全局
    // QQmlContext* context = engine.rootContext();
    // // Initialize NodeControllerManager
    // NodeControllerManager nodeControllerManager;
    // context->setContextProperty("nodeControllerManager", &nodeControllerManager);

    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(
        &engine,
        &QQmlApplicationEngine::objectCreated,
        &app,
        [url](QObject *obj, const QUrl &objUrl) {
            if (!obj && url == objUrl)
                QCoreApplication::exit(-1);
        },
        Qt::QueuedConnection);
    engine.load(url);

    return app.exec();
}
